import router from '@/router'
import nProgress from 'nprogress'
import 'nprogress/nprogress.css'
import store from '@/store'
import { asyncRoutes } from '@/router'

const whiteList = ['/login', '/404']
// 前置路由守卫
router.beforeEach(async(to, from, next) => {
  nProgress.start()
  // 存在token
  if (store.getters.token) {
    if (to.path === '/login') {
      next('/') // 中转到主页
      nProgress.done()
    } else {
      if (!store.getters.userId) {
        const { roles } = await store.dispatch('user/getUserInfoAction')
        const filterRoutes = asyncRoutes.filter(item => {
          return roles.menus.includes(item.name)
        })// 筛选后的路由
        store.commit('user/setRoutes', filterRoutes)
        router.addRoutes([...filterRoutes, { path: '*', redirect: '/404', hidden: true }])
        // router添加动态路由之后 需要转发一下
        next(to.path) // 目的是让路由拥有信息 router的已知缺陷
      } else {
        next()
      }
    }
    
  } else {  // 没有token
    if (whiteList.includes(to.path)) {
      next() // 放行
    } else {
      next('/login')
      nProgress.done()
    }
  }
})

// 后置路由守卫
router.afterEach(() => {
  nProgress.done()
})
